import fs from '@ohos.file.fs';

export class path {
  private static readonly extensionReg = new RegExp('\.([^\/]+)$', 'g');
  private static readonly fileNameReg = new RegExp('\/([^\/]+(\.[^\/]+)?)$', 'g');
  private static readonly fileNameWithoutExtensionReg = new RegExp('\/([^\/]+?)(\.[^\/]+)?$', 'g');

  static join(...path: string[]) {
    return path.join('/').replace(new RegExp('\/+', 'g'), '/');
  }

  static async exists(path: string) {
    try {
      return await fs.access(path);
    } catch (err) {
      return false;
    }
  }

  static existsSync(path: string) {
    try {
      return fs.accessSync(path);
    } catch (err) {
      return false;
    }
  }

  static getFileName(src: string) {
    const matches = src.trim().match(path.fileNameReg);
    return matches[1]?.toString();
  }

  static getFileNameWithoutExtension(src: string) {
    const matches = src.trim().match(path.fileNameWithoutExtensionReg);
    return matches[1]?.toString();
  }

  static getExtension(src: string) {
    const matches = src.trim().match(path.extensionReg);
    return matches[1]?.toString();
  }

  static generateUniqueFilename(basePath: string, baseName: string, ext: string) {
    let counter = 1;
    let fullPath = path.join(basePath, `${baseName}${ext}`);
    while (path.existsSync(fullPath)) {
      fullPath = path.join(basePath, `${baseName} (${counter})${ext}`);
      counter++;
    }
    return fullPath;
  }
}